package photobox.manage

import grails.transaction.Transactional
import photobox.photo.PhotoComment
import photobox.utils.HQLUtils


@Transactional
class CommentService {

    def list(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from PhotoComment A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.comment) {
            hql += " and " + HQLUtils.whereCondition("A.comment", searchParam.comment.opt, "comment")
            params.comment = searchParam.comment.data
        }
        if (searchParam.dateCreated) {
            hql += " and " + HQLUtils.whereCondition("A.dateCreated", searchParam.dateCreated.opt, "dateCreated")
            params.dateCreated = searchParam.dateCreated.data
        }
        if (searchParam.user) {
            hql += " and " + HQLUtils.whereCondition("A.user", searchParam.user.opt, "user")
            params.user = searchParam.user.data
        }
        if (searchParam.photo) {
            hql += " and " + HQLUtils.whereCondition("A.photo", searchParam.photo.opt, "photo")
            params.photo = searchParam.photo.data
        }
        if (searchParam.isRecommend) {
            hql += " and " + HQLUtils.whereCondition("A.isRecommend", searchParam.isRecommend.opt, "isRecommend")
            params.isRecommend = searchParam.isRecommend.data
        }

        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = PhotoComment.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = PhotoComment.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
}
